<template>
	<view class="page-container back-grey">
		<!-- 订单信息 -->
		<view class="prow-l back-white mb-l" style="padding-top: 20rpx;padding-bottom: 10rpx;">
			<view class="row-box sb mb-10">
				<text>订单信息</text>
				<text class="s24 grey-light">订单编号：{{ merOrderNo }}</text>
			</view>
			<view class="prow-s">
				<cd-petcard-order :pet="pet" :showShop="false" :showArrow="false"></cd-petcard-order>
			</view>
		</view>
		
		<!-- 内容 -->
		<view class="pall-l back-white">
			<!-- 评分 -->
			<view class="row-box mb-10">
				<text class="grey-dark mr-10">评分</text>
				<u-rate :count="5" v-model="rate" :min-count="1" active-color="#f9d002" size="36" gutter="16" :disabled="id"></u-rate>
				<text class="grey-dark ml-10">{{ rateText }}</text>
			</view>
			<!-- 上传图片区域 -->
			<scroll-view v-if="!id || (id && images.length)" scroll-x="true" style="white-space: nowrap;">
				<view class="pcol-l upload-grid">
					<view v-for="(item, index) in images" :key="index" class="upload-item">
						<image class="upload-image" :src="item" mode="aspectFill" @click.stop="previewImage(index, images)"></image>
						<view v-if="!id" class="row-box center radius-circle icon-box">
							<u-icon name="close" color="#ffffff" size="28" :bold="true" @click.stop="removeImage(index)"></u-icon>
						</view>
					</view>
					<view v-if="images.length<limit && !id" class="upload-item" @click="selectUploadHandle()">
						<image class="upload-image" src="/static/icon/upload.png" mode="aspectFill"></image>
					</view>
				</view>
			</scroll-view>
			<!-- 备注详情 -->
			<view v-if="!id || (id && detail)" class="mt-base">
				<cd-form-info type="textarea" attrName="detail" :attrValue.sync="detail" :maxlength="100" :bgClass="id?'back-white':''"
					placeholder="请输入评价内容..." :unEdit="id">
				</cd-form-info>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view v-if="!id" class="submit-button-box">
			<view class="submit-button back-primary" @click="submitHandle()">提交</view>
		</view>
	</view>
</template>

<script>
	import env from '@/utils/env.js'
	export default {
		data() {
			return {
				merOrderNo: '', // 订单编号
				merchantId: '', // 商家id
				pet: {}, // 宠物对象
				qntoken: '',  // 七牛云上传token
				limit: 6, // 限制上传数量
				images: [], // 选择上传的临时图片劣币表
				uploads: [],  // 上传后列表
				detail: '', // 备注
				rate: 5, // 评分
				id: 1, // 订单id,不为空则已评价
			};
		},
		computed: {
			// 评分文字
			rateText() {
				if (this.rate>4) {
					return '非常满意'
				} else if (this.rate>2) {
					return '满意'
				} else {
					return '一般'
				}
			}
		},
		watch: {
			// 侦听图片上传后地址列表
			uploads(newValue, oldValue) {
				if ((newValue.length == this.images.length) && this.images.length!=0) {
					// 上传完所有图片
					// 调用提交接口
					this.submit()
				}
			},
		},
		onLoad(options) {
			this.merOrderNo = options.id
			this.merchantId = options.merchantId
			this.pet = JSON.parse(decodeURIComponent(options.pet))
			// 获取七牛上传使用TOKEN
			this.getUploadToken()
			// 获取用户评价
			this.getCommentInfo()
		},
		methods: {
			// 选择上传前
			async selectUploadHandle() {
				if (this.id) return
				this.images = [...this.images, ...await this.chooseImages(this.limit-this.images.length)]
			},
			
			// 点击提交
			submitHandle() {
				if (!this.detail) {
					return uni.showToast({
						icon: 'none',
						title: '请输入评价内容！'
					})
				}
				
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				
				// 获取临时文件列表长度
				const length = this.images.length
				
				if (length > 0) { // 如果用户选择了图片
					// 先上传图片，上传完所有图片再调用提交的接口
					this.images.forEach((tempPath, index) => {
						let pathArr = tempPath.split('.')
						let extra = pathArr[pathArr.length-1]
						// 获得唯一标识码
						let uniqueCode = this.generateUUID()
						// case 'ECN': uploadURL = 'https://up.qiniup.com'
						// case 'NCN': uploadURL = 'https://up-z1.qiniup.com'
						// case 'SCN': uploadURL = 'https://up-z2.qiniup.com'
						// case 'NA': uploadURL = 'https://up-na0.qiniup.com'
						// case 'ASG': uploadURL = 'https://up-as0.qiniup.com'
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com',
							filePath: tempPath,
							name: 'file',
							formData: {
								'key': uniqueCode + '.' + extra,
								'token': this.qntoken,
							},
							success: (res) => {
								console.log('uni.uploadFile', res)
								let strToObj = JSON.parse(res.data)
								let backUrl = env.imageUrl + strToObj.key
								// 处理上传成功后的返回值
								this.uploads.push(backUrl)
							},
							fail: (err) => {
								console.log('uni.uploadFile', err)
								uni.hideLoading()
								uni.showToast({
									icon: 'none',
									title: '提交失败！'
								})
							}
						})
					})
				} else {
					// 提交接口
					this.submit()
				}
			},
			
			// 提交接口
			submit() {
				let params = {}
				params['anonymity'] = 0
				params['commentType'] = 3
				params['content'] = this.detail
				if (this.uploads.length) params['image'] = this.uploads.join(',')
				params['isAdd'] = 0
				params['merchantId'] = this.merchantId
				params['orderSn'] = this.merOrderNo
				params['starNum'] = this.rate
				this.$api.AddComment(params).then(res => {
					console.log('AddComment-success', res)
					uni.hideLoading()
					if (res.data.code == 200) {
						uni.showToast({
							icon: 'none',
							title: '提交成功！',
							success: () => {
								setTimeout(() => {
									uni.navigateBack()
								}, 500)
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('AddComment-fail', err)
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '提交失败！'
					})
				})
			},
			
			// 获取用户评价
			getCommentInfo() {
				this.$api.GetCommentInfo({
					orderNo: this.merOrderNo,
					merchantId: this.merchantId
				}).then(res => {
					console.log('GetCommentInfo-success', res)
					if (res.data.code == 200) {
						if (res.data.data == null || res.data.data.id == null) return this.id = ''
						this.id = res.data.data.id
						this.detail = res.data.data.content
						this.rate = res.data.data.starNum
						if (res.data.data.image) {
							this.images = res.data.data.image.split(',')
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg,
							success: () => {
								setTimeout(() => {
									uni.navigateBack()
								}, 200)
							}
						})
					}
				}).catch(err => {
					console.log('GetCommentInfo-fail', err)
				}).finally(() => {
					
				})
			}
		},
	}
</script>

<style lang="scss">
.page-container {
	padding-top: $uni-spacing-col-l;
	
}
</style>
